package com.devilvan.betrice.recruitment.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.devilvan.betrice.recruitment.mapper.BossWelfareMapper;
import com.devilvan.betrice.recruitment.po.BossWelfarePo;
import com.devilvan.betrice.recruitment.repository.BossWelfareRepository;
import com.devilvan.betrice.recruitment.service.BossWelfareService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Evad.Wu
 * @Description Boss直聘 招聘信息-福利信息 业务逻辑类
 * @date 2022-08-08
 */
@Service
public class BossWelfareServiceImpl extends ServiceImpl<BossWelfareMapper, BossWelfarePo> implements BossWelfareService {
    @Resource(name = "bossWelfareRepository")
    private BossWelfareRepository bossWelfareRepository;

    @Override
    public Set<BossWelfarePo> checkSaveWelfares(Set<String> welfares) {
        Set<BossWelfarePo> bossWelfarePoSet = new HashSet<>();
        Set<BossWelfarePo> welfarePoSet = Optional.of(welfares).map(m -> {
            Set<BossWelfarePo> set = null;
            if (!m.isEmpty()) {
                set = this.findByWelfareIn(m);
            }
            return set;
        }).orElseGet(HashSet::new);
        if (welfarePoSet.isEmpty()) {
            bossWelfarePoSet = welfares.stream().map(m -> new BossWelfarePo(m.trim())).collect(Collectors.toSet());
        } else {
            Set<String> welfareSet = welfarePoSet.stream().map(BossWelfarePo::getWelfare).collect(Collectors.toSet());
            Collection<String> intersection = CollUtil.disjunction(welfares, welfareSet);
            if (!intersection.isEmpty()) {
                bossWelfarePoSet = intersection.stream().map(m -> new BossWelfarePo(m.trim())).collect(Collectors.toSet());
                welfarePoSet.addAll(bossWelfarePoSet);
            }
        }
        bossWelfareRepository.saveAllAndFlush(bossWelfarePoSet);
        return welfarePoSet;
    }

    public Set<BossWelfarePo> findByWelfareIn(Set<String> welfares) {
        LambdaQueryWrapper<BossWelfarePo> queryWrapper = new QueryWrapper<BossWelfarePo>().lambda();
        queryWrapper.in(BossWelfarePo::getWelfare, welfares);
        queryWrapper.groupBy(BossWelfarePo::getWelfare);
        return new HashSet<>(this.list(queryWrapper));
    }
}
